<template>
  <div class="sticky-header-container">
    <div ref="stick_con" :style="{ height: isFixed ? headerHeight + 'px' : 0 }"></div>
    <div
      ref="stick_slot"
      :class="['sticky-header ml-5', { 'is-fixed': isFixed }]"
      :style="stickyStyles"
    >
      <slot></slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, useTemplateRef } from "vue";
import { throttle } from "lodash-es";

const props = defineProps({
  top: {
    type: Number,
    default: 0,
  },
});
const isFixed = ref<boolean>(false);

const headerHeight = ref<number>(0);
const stick_con = useTemplateRef<HTMLElement>("stick_con");
const stick_slot = useTemplateRef<HTMLElement>("stick_slot");

const stickyStyles = ref<any>({});

const handleScroll = throttle(
  () => {
    // const scrollTop: number = window.pageYOffset || document.documentElement.scrollTop;
    const react = stick_con.value!.getBoundingClientRect();
    if (react.top < props.top && isFixed.value === false) {
      const relDiv = stick_slot.value?.getBoundingClientRect();
      if (relDiv) {
        headerHeight.value = relDiv.height;
      }
      isFixed.value = true;
      stickyStyles.value = {
        position: "fixed",
        top: props.top + "px",
        zIndex: 1000,
        boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
      };
    }
    if (react.top >= props.top && isFixed.value === true) {
      isFixed.value = false;
      headerHeight.value = 0;
      stickyStyles.value = {};
    }
    // console.log(31);
  },
  100,
  {
    leading: true,
    trailing: true,
  }
);

onMounted((): void => {
  window.addEventListener("scroll", handleScroll);
});

onUnmounted((): void => {
  window.removeEventListener("scroll", handleScroll);
});
</script>

<style scoped>
.sticky-header-container {
  position: relative;
}

.sticky-header {
  transition: all 0.3s ease;
}

.sticky-header.is-fixed {
  background-color: white; /* 可根据需要调整背景色 */
}
</style>
